<template>
  <a-modal
    :title="title"
    :open="visible"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    width="600px"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <!-- 编辑时显示销售单号 -->
      <a-form-item v-if="form.salesOrderId" label="销售单号" name="salesOrderNo">
        <span>{{ form.salesOrderNo }}</span>
      </a-form-item>

      <!-- 编辑时显示销售人员 -->
      <a-form-item v-if="form.salesOrderId" label="销售人员" name="salespersonName">
        <span>{{ form.salespersonName || '暂无' }}</span>
      </a-form-item>

      <a-form-item label="客户" name="customerId">
        <a-select
          v-model:value="form.customerId"
          placeholder="请选择客户"
          show-search
          option-filter-prop="label"
        >
          <a-select-option
            v-for="customer in customerList"
            :key="customer.customerId"
            :value="customer.customerId"
            :label="customer.customerName"
          >
            {{ customer.customerName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="销售额" name="salesAmount">
        <a-input-number
          v-model:value="form.salesAmount"
          placeholder="请输入销售额"
          :min="0"
          :precision="2"
          style="width: 100%"
        />
      </a-form-item>

      <a-form-item label="状态" name="status">
        <a-select v-model:value="form.status" placeholder="请选择状态">
          <a-select-option v-for="item in salesOrderStatusOptions" :key="item.value" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="备注" name="remark">
        <a-textarea v-model:value="form.remark" placeholder="请输入备注" :rows="3" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import type { SalesOrder } from '@/types/sales-order'
import { salesOrderStatusOptions, SalesOrderStatus } from '@/types/sales-order'
import type { Customer } from '@/types/customer'
import * as salesOrderApi from '@/api/sales-order'
import * as customerApi from '@/api/customer'

interface Props {
  visible: boolean
  formData?: Partial<SalesOrder>
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  formData: () => ({})
})

const emit = defineEmits<Emits>()

// 表单相关
const formRef = ref<FormInstance>()
const loading = ref(false)

// 客户列表
const customerList = ref<Customer[]>([])

// 表单数据
const form = reactive<Partial<SalesOrder>>({
  salesOrderId: undefined,
  customerId: undefined,
  salesAmount: undefined,
  status: SalesOrderStatus.COMPLETED, // 默认完结
  remark: ''
})

// 表单标题
const title = computed(() => {
  return props.formData.salesOrderId ? '编辑销售订单' : '新增销售订单'
})

// 表单验证规则
const rules: Record<string, Rule[]> = {
  customerId: [
    { required: true, message: '请选择客户', trigger: 'change' }
  ],
  salesAmount: [
    { required: true, message: '请输入销售额', trigger: 'blur' },
    { type: 'number', min: 0, message: '销售额必须大于等于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 加载客户列表
const loadCustomerList = async () => {
  try {
    const customers = await customerApi.getCustomerList()
    customerList.value = customers || []
  } catch (error) {
    console.error('加载客户列表失败:', error)
  }
}

// 监听formData变化，填充表单
watch(() => props.formData, (newVal) => {
  if (newVal) {
    // 使用 Object.assign 确保所有字段都被正确赋值，包括 salesOrderId
    // 确保 salesAmount 转换为数字类型
    Object.assign(form, {
      salesOrderId: newVal.salesOrderId,
      salesOrderNo: newVal.salesOrderNo,
      salespersonId: newVal.salespersonId,
      salespersonName: newVal.salespersonName,
      customerId: newVal.customerId,
      salesAmount: newVal.salesAmount != null ? Number(newVal.salesAmount) : undefined,
      status: newVal.status !== undefined ? newVal.status : SalesOrderStatus.COMPLETED,
      remark: newVal.remark || ''
    })
  } else {
    // 重置表单
    Object.assign(form, {
      salesOrderId: undefined,
      salesOrderNo: undefined,
      salespersonId: undefined,
      salespersonName: undefined,
      customerId: undefined,
      salesAmount: undefined,
      status: SalesOrderStatus.COMPLETED,
      remark: ''
    })
  }
}, { immediate: true, deep: true })

// 监听visible变化，重置表单
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    formRef.value?.resetFields()
  }
})

// 初始化
onMounted(() => {
  loadCustomerList()
})

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    if (form.salesOrderId) {
      // 编辑：调用更新接口
      await salesOrderApi.updateSalesOrder({ ...form, salesOrderId: form.salesOrderId })
    } else {
      // 新增：调用新增接口
      await salesOrderApi.addSalesOrder(form)
    }

    message.success(`${title.value}成功`)
    emit('success')
  } catch (error) {
    message.error(`${title.value}失败`)
    console.error(`${title.value}失败:`, error)
  } finally {
    loading.value = false
  }
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
}
</script>

